#!/usr/bin/python3
#coding=utf-8

"""
目标进程的监控文件，使用死循环睡眠唤醒的方式实现
"""

import subprocess
from subprocess import PIPE
from setting import *
import loggers
import time

logger = loggers.get_logger('start_script.son')
# print(__name__)


def check_pid():
    result = check(PATHPID)
    return result

def check_cpid():
    result = check(CPATHPID)
    return result

def start_target():
    result = start_pid(CMD,PATHPID)
    return result

def start_control():
    result = start_pid(CCMD,CPATHPID)
    return result

def check_pidname():
    '''
    通过进程的名字来查询该进程是否存在，如果存在返回True，不存在返回False
    :return:
    '''
    try:
        # 查询该进程是否存在
        p_check = subprocess.Popen("ps aux | grep '%s'"%CMD,shell=True,stdout=subprocess.PIPE)
        if len(p_check.stdout.readlines()) < 3:
            return False
        else:
            return True
    except Exception as e:
        logger.error(e)

def check(pathfile:str):
    '''
    通过进程文件获取进程号，通过进程号查询是否存在该进程
    :param pathfile:
    :return:
    '''
    try:
        # 获取进程文件的进程号
        with open(pathfile,'r',encoding='utf-8') as f:
            pid_str = f.read()
            if pid_str:
                # 查询该进程是否存在
                cmd = 'ps aux | grep ' + str(pid_str)
                p_check = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE)
                lists_pid = [i.strip() for i in p_check.stdout.readlines()[0].decode('utf-8').split("  ")]
                # 如果进程不存在，启动进程
                if pid_str.strip() not in lists_pid:
                    return False,0
                else:
                    return True,pid_str
            else:
                return False,0
    except Exception as e:
        logger.error(e)

def start_pid(cmd:str,path:str):
    '''
    开启默认的进程
    :return:
    '''
    try:
        # 打开目标程序
        p_torget = subprocess.Popen(cmd, shell=True, stdout=PIPE)
        logger.info(p_torget.stdout.read())
        # 将目标进程号写入文件
        with open(path, 'w', encoding='utf-8') as f:
            f.write(str(p_torget.pid))
        return str(p_torget.pid)
    except Exception as e:
        logger.error(e)
        return None

def stop_pid(pid:str):
    '''
    杀死进程
    :return:
    '''
    try:
        cmd = 'kill -9 ' + str(pid)
        p_torget = subprocess.Popen(cmd, shell=True, stdout=PIPE)
        logger.info(p_torget.stdout.read())
    except Exception as e:
        logger.error(e)



def control_run():
    while True:
        if not check_pid()[0]:
            start_control()
        time.sleep(TIME)



if __name__ == '__main__':
    # test_name()
    control_run()
